#include "compression.h"


int Compresser(char * inputFileName, char * outputFileName){
    
    
    clock_t t1, t2;
    
    t1 = clock();
    
    FILE * inputFile;
    FILE * outputFile;
    
    inputFile = open_in(inputFileName);
    outputFile = open_out(outputFileName);
    
    Initialiser();
    printf("[INFO] Initialisation du dictionnaire\n");
    
    int n = 9; // taille des bits a rentrer
    int L_MAX = 10; // pour changer le malloc du w
    int cpt =1;
    
    cellule *a = initCell(1);
    cellule *w=NULL;
    cellule *w_bis;
    cellule *tmp;

    w = initCell(100);
    
    w->sequence[0] = fgetc(inputFile);
    w->taille = 1;
    a->sequence[0] = fgetc(inputFile);
    
    printf("[INFO] Debut de la lecture du fichier: %s\n",inputFileName);
    
    while( (!feof(inputFile))){
        
        a->taille=1;
        tmp = initCell(100);
        cellcpy(tmp,w);
        cellule * machin = cellcat(tmp,a);
        if (SequenceVersCode(machin->sequence,tmp->taille)!=(-1)) {  
                cpt++;
                w_bis = initCell(200);
                cellcpy(w_bis,w);
                free(w);
                w=initCell(10*cpt);
                cellcpy(w,w_bis);
                
            w = cellcat(w,a);
        }
        else {
            
            if(SequenceVersCode(w->sequence,w->taille) > (pow(2,n)-1) ){
                n = n + 1;
                //fprintf(outputFile,"%d ",256);
                printf("[INFO] Taille d'ecriture(+1): %d bits\n",n);
            }
    
            fprintf(outputFile,"%d ",SequenceVersCode(w->sequence,w->taille));
            Inserer(SequenceVersCode(w->sequence,w->taille),SequenceVersCode(a->sequence,a->taille));
            free(w);
            w = initCell(1);
            w=cellcpy(w,a);
            cpt =1;
        }
        a->sequence[0] = fgetc(inputFile);
    }
    //fprintf(outputFile,"%d ",SequenceVersCode(w->sequence,w->taille));
    //fprintf(outputFile,"%d ",257);     
    
    printf("[INFO] Fin de lecture du fichier: %s \n",inputFileName);
    
    fseek(inputFile,0,SEEK_END); 
    tailleInFile=ftell(inputFile);
    
    fseek(outputFile,0,SEEK_END); 
    tailleOutFile=ftell(outputFile);
    
    fclose(outputFile);
    fclose(inputFile);
     
    t2 = clock();
    temps_compression = (float)(t2-t1)/CLOCKS_PER_SEC;
    
    
    
    return NO_ERROR;

}
